package com.myproject.myblogserver.controller;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;

import com.myproject.myblogserver.contant.CommonConstants;
import com.myproject.myblogserver.dto.comment.CommentReplyDTO;
import com.myproject.myblogserver.entity.BlogComment;
import com.myproject.myblogserver.entity.CommentReply;
import com.myproject.myblogserver.service.IBlogCommentService;
import com.myproject.myblogserver.service.ICommentReplyService;
import com.myproject.myblogserver.utils.JwtUtil;

/**
 * <p>
 * 回复评论表 前端控制器
 * </p>
 *
 * @author jiangweike
 * @since 2025-02-16
 */
@Controller
@RequestMapping("/commentReply")
public class CommentReplyController {

    @Autowired
    private ICommentReplyService commentReplyService;

    @Autowired
    private IBlogCommentService blogCommentService;

    /**
     * 添加回复
     */
    @PostMapping("/add")
    public ResponseEntity<?> addReply(@RequestBody CommentReplyDTO replyDTO,
            @RequestHeader("Authorization") String authHeader) {
        try {
            var userId = JwtUtil.extractUserIdFromAuthHeader(authHeader);
            var commentReply = new CommentReply();

            // 验证原评论是否存在
            var comment = blogCommentService.lambdaQuery()
                    .eq(BlogComment::getIsDeleted, CommonConstants.DELETED_STATUS_NO)
                    .eq(BlogComment::getId, replyDTO.getCommentId())
                    .one();

            if (comment == null) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("原评论不存在！");
            }

            // 如果是回复其他回复，验证父回复是否存在
            if (replyDTO.getParentReplyId() != null) {
                var parentReply = commentReplyService.lambdaQuery()
                        .eq(CommentReply::getIsDeleted, CommonConstants.DELETED_STATUS_NO)
                        .eq(CommentReply::getId, replyDTO.getParentReplyId())
                        .one();               

                if (parentReply == null) {
                    return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("被回复的评论不存在！");
                }
            }
            
            BeanUtils.copyProperties(replyDTO, commentReply);
            // 设置回复者ID
            commentReply.setUserId(userId);
            
            // 保存回复
            commentReplyService.save(commentReply);

            return ResponseEntity.ok("回复成功！");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("回复失败！");
        }
    }

    /**
     * 删除回复
     */
    @PostMapping("/delete/{replyId}")
    public ResponseEntity<?> deleteReply(@PathVariable Long replyId,
            @RequestHeader("Authorization") String authHeader) {
        try {
            var userId = JwtUtil.extractUserIdFromAuthHeader(authHeader);

            // 验证回复是否存在且属于当前用户
            var reply = commentReplyService.lambdaQuery()
                    .eq(CommentReply::getIsDeleted, CommonConstants.DELETED_STATUS_NO)
                    .eq(CommentReply::getId, replyId)
                    .one();

            if (reply == null) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("回复不存在！");
            }

            if (!reply.getUserId().equals(userId)) {
                return ResponseEntity.status(HttpStatus.FORBIDDEN).body("无权删除此回复！");
            }

            // 软删除回复
            commentReplyService.lambdaUpdate()
                    .set(CommentReply::getIsDeleted, CommonConstants.DELETED_STATUS_YES)
                    .eq(CommentReply::getId, replyId)
                    .update();

            return ResponseEntity.ok("删除回复成功！");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("删除回复失败！");
        }
    }
}
